package cn.homework.mvcboot.controller;

import cn.homework.mvcboot.common.response.JsonResult;
import cn.homework.mvcboot.common.response.StatusCode;
import cn.homework.mvcboot.pojo.dto.UserArticleDTO;
import cn.homework.mvcboot.pojo.dto.UserLoginDTO;
import cn.homework.mvcboot.pojo.entity.Article;
import cn.homework.mvcboot.pojo.mapper.UserMapper;
import cn.homework.mvcboot.pojo.vo.ArticleVO;
import cn.homework.mvcboot.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/v1/users/")
@Validated
@Api(tags = "用户模块")
public class UserController {
    // 自动装配
    @Autowired
    private UserMapper userMapper;

    // 登录接口
    @PostMapping("login")
    @ApiOperation(value = "用户登录接口")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){

        log.debug("userLoginDTO:{}",userLoginDTO);

        //  查询接口
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginDTO);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        session.setAttribute("user",userVO);
        return JsonResult.success();
    }

    // 发布文章接口
    @PostMapping("article")
    @ApiOperation(value = "发布文章接口")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){

        log.debug("userArticleDTO:{}",userArticleDTO);

        // 通过会话获取用户信息
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }

        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());

        userMapper.insertArticle(article);

        return JsonResult.success();
    }

    // 通过id获取文章信息
    @GetMapping("selectById")
    @ApiOperation(value = "通过id获取文章信息")
    public JsonResult selectById(@RequestParam("id")
            @Range(min = 1,max = 200, message = "id必须在1到200之间")
                                     Long id){
        log.debug("id:{}",id);
        ArticleVO articlevo = userMapper.selectById(id);

        return JsonResult.success(articlevo);
    }














}
